package middol.test

import grails.converters.JSON
import middol.base.GlobalExceptionHandle
import middol.utils.MeiliSearchUtils
import middolmeilisearch.SearchQuery
import org.springframework.beans.factory.annotation.Autowired

class MeiliSearchController implements GlobalExceptionHandle{
	static responseFormats = ['json', 'xml']
    @Autowired
    MeiliSearchUtils meiliSearchUtils
    /**
     * 获取所有indexes
     * @render
     */
    def getAllIndexes(){
        render meiliSearchUtils.getAllIndexes() as JSON
    }
    /**
     * 创建 index
     * @param record
     * @render
     */
    def createIndex(){
        render meiliSearchUtils.createIndex(request.JSON) as JSON
    }
    /**
     * 获取index
     * @param uid
     * @render
     */
    def getIndex(String uid){
        render meiliSearchUtils.getIndex(params.uid) as JSON
    }
    /**
     * 更新 index primary key
     * @param uid
     * @param record
     * @render
     */
    def updateIndexPrimaryKey(){
        def record = request.JSON
        render meiliSearchUtils.updateIndexPrimaryKey(record.uid, record) as JSON
    }
    /**
     * 删除 index
     * @param uid
     * @render
     */
    def deleteIndex(){
        render meiliSearchUtils.deleteIndex(params.uid) as JSON
    }
    /**
     * 获取单个document
     * @param uid
     * @param identifier
     * @render
     */
    def getDocument(){
        render meiliSearchUtils.getDocument(params.uid, params.identifier) as JSON
    }
    /**
     * 获取所有document
     * @param uid
     * @render
     */
    def getDocuments(){
        render meiliSearchUtils.getDocuments(params.uid) as JSON
    }
    /**
     * 获取所有document 分页
     * @param uid
     * @param limit
     * @render
     */
    def getDocumentsLimit(){
        render meiliSearchUtils.getDocumentsLimit(params.uid, params.limit as int) as JSON
    }
    /**
     * 批量添加 document
     * @param uid
     * @param document
     * @render
     */
    def addDocuments(){
        def record = request.JSON
        render meiliSearchUtils.addDocuments(record.uid, record.document) as JSON
    }
    /**
     * 删除单个document
     * @param uid
     * @param identifier
     * @render
     */
    def deleteDocument(){
        render meiliSearchUtils.deleteDocument(params.uid, params.identifier) as JSON
    }
    /**
     * 删除所有document
     * @param uid
     * @render
     */
    def deleteDocuments(){
        render meiliSearchUtils.deleteDocuments(params.uid) as JSON
    }
    /**
     * 搜索
     * @param uid
     * @param searchQuery
     * @render
     */
    def search(){
        SearchQuery searchQuery = new SearchQuery(request.JSON)
        render meiliSearchUtils.search(params.uid, searchQuery.getQuery()) as JSON
    }

    def getUpdate() {
        render meiliSearchUtils.getUpdate(params.uid, params.updateId) as JSON
    }

    def getUpdates(){
        render meiliSearchUtils.getUpdates(params.uid) as JSON
    }
}
